from rest_framework.views import Response
from rest_framework.views import exception_handler as drf_exception_handler

from utils import logging

logger = logging.get_logger()


def exception_handler(exc, context):
    response = drf_exception_handler(exc, context)
    if response is None:
        response = Response({'code': 999, 'msg': '服务器异常，请重试...'})
    else:
        try:
            msg = response.data['detail']
        except Exception:
            msg = '未知异常'
        response = Response({'code': 998, 'msg': msg})
    logger.critical('%s' % exc)
    return response
